package com.ruoyi.safe.controller.api;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.config.MinIoProperties;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MinIoUtil;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.safe.domain.BizEducateDocAttach;
import com.ruoyi.safe.domain.BizSafeAttach;
import com.ruoyi.safe.domain.BizSafeDocAttach;
import com.ruoyi.safe.domain.vo.BizEducateDocAttachVO;
import com.ruoyi.safe.domain.vo.ListRequestVo;
import com.ruoyi.safe.service.IBizEducateDocAttachService;
import com.ruoyi.safe.service.IBizSafeAttachService;
import com.ruoyi.safe.service.IBizSafeDocAttachService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 手机端-上传接口
 *
 * @Auther: lihongming
 * @Date: 2023-11-20 10:11
 * @Description: com.ruoyi.safe.controller.api
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Autowired
    MinIoProperties minIoProperties;
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    IBizSafeAttachService bizSafeAttachService;
    @Autowired
    IBizSafeDocAttachService bizSafeDocAttachService;

    @Autowired
    IBizEducateDocAttachService bizEducateDocAttachService;

    /**
     * 检查图片上传
     */
    @PostMapping("/uploadSafe")
    public AjaxResult uploadSafe(@RequestParam("file") MultipartFile file, @RequestParam("projectId") Long projectId, @RequestParam("userName") String userName) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                SysUser sysUser = sysUserService.selectUserByUserName(userName);
                if (sysUser == null) {
                    throw new Exception(StringUtils.format("用户信息不存在：{}", userName));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                Long userId = sysUser.getUserId();

                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        userId,
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketName(), fileName, file.getInputStream());
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("fileName", fileName);

                BizSafeAttach bizSafeAttach = BizSafeAttach.builder()
                        .id(IdUtil.getSnowflakeNextId())
                        .bucket(minIoProperties.getBucketName())
                        .name(fileName)
                        .size(file.getSize())
                        .type(file.getContentType())
                        .projectId(projectId)
                        .build();
                bizSafeAttach.setCreateBy(sysUser.getUserName());
                bizSafeAttach.setCreateTime(DateUtils.getNowDate());
                bizSafeAttachService.insertBizSafeAttachNoLogin(bizSafeAttach);

                return ajax;
            } else {
                return AjaxResult.error("上传文件不能为空，请联系管理员");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 检查图片上传(formData)
     */
    @PostMapping("/uploadSafeFormData")
    public AjaxResult uploadSafeFormData(@RequestParam("file") MultipartFile file, @ModelAttribute ListRequestVo listRequestVo) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                SysUser sysUser = sysUserService.selectUserByUserName(listRequestVo.getUserName());
                if (sysUser == null) {
                    throw new Exception(StringUtils.format("用户信息不存在：{}", listRequestVo.getUserName()));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                Long userId = sysUser.getUserId();

                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        userId,
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketName(), fileName, file.getInputStream());
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("bucket",minIoProperties.getBucketName());
                ajax.put("fileName", fileName);

                BizSafeAttach bizSafeAttach = BizSafeAttach.builder()
                        .id(IdUtil.getSnowflakeNextId())
                        .bucket(minIoProperties.getBucketName())
                        .name(fileName)
                        .size(file.getSize())
                        .type(file.getContentType())
                        .projectId(listRequestVo.getProjectId())
                        .build();
                bizSafeAttach.setCreateBy(sysUser.getUserName());
                bizSafeAttach.setCreateTime(DateUtils.getNowDate());
                int i = bizSafeAttachService.insertBizSafeAttachNoLogin(bizSafeAttach);
                if (i > 0) {
                    return ajax;
                } else {
                    return AjaxResult.error("文件上传失败，请重试");
                }

            } else {
                return AjaxResult.error("上传文件不能为空");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 工程内业资料上传
     */
    @PostMapping("/uploadSafeDoc")
    public AjaxResult uploadSafeDoc(@RequestParam("file") MultipartFile file, @ModelAttribute ListRequestVo listRequestVo) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                SysUser sysUser = sysUserService.selectUserByUserName(listRequestVo.getUserName());
                if (sysUser == null) {
                    throw new Exception(StringUtils.format("用户信息不存在：{}", listRequestVo.getUserName()));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        sysUser.getUserId(),
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketSafeDoc(), fileName, file.getInputStream());
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("fileName", fileName);
                ajax.put("bucket", minIoProperties.getBucketSafeDoc());
                //TODO 工程内业资料入库
                BizSafeDocAttach bizSafeDocAttach = BizSafeDocAttach.builder()
                        .id(IdUtil.getSnowflakeNextId())
                        .bucket(minIoProperties.getBucketSafeDoc())
                        .displayName(FilenameUtils.getBaseName(file.getOriginalFilename()))
                        .realName(fileName)
                        .extName(suffixName)
                        .type(file.getContentType())
                        .projectId(listRequestVo.getProjectId())
                        .build();
                bizSafeDocAttach.setCreateBy(sysUser.getUserName());
                bizSafeDocAttach.setCreateTime(DateUtils.getNowDate());
                int i=bizSafeDocAttachService.insertBizSafeDocAttachNoLogin(bizSafeDocAttach);
                if (i > 0) {
                    return ajax;
                } else {
                    return AjaxResult.error("文件上传失败，请重试");
                }
            } else {
                return AjaxResult.error("上传文件不能为空，请联系管理员");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 教育资料上传
     */
    @PostMapping("/uploadEducateDoc")
    public AjaxResult uploadEducateDoc(@RequestParam("file") MultipartFile file, @ModelAttribute ListRequestVo listRequestVo) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                SysUser sysUser = sysUserService.selectUserByUserName(listRequestVo.getUserName());
                if (sysUser == null) {
                    throw new Exception(StringUtils.format("用户信息不存在：{}", listRequestVo.getUserName()));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        sysUser.getUserId(),
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketEdu(), fileName, file.getInputStream());
                BizEducateDocAttach bizEducateDocAttach = BizEducateDocAttach.builder()
                        .id(IdUtil.getSnowflakeNextId())
                        .bucket(minIoProperties.getBucketEdu())
                        .size(file.getSize())
                        .displayName(FilenameUtils.getBaseName(file.getOriginalFilename()))
                        .realName(fileName)
                        .extName(suffixName)
                        .type(file.getContentType())
                        .projectId(listRequestVo.getProjectId())
                        .build();
                bizEducateDocAttach.setCreateBy(sysUser.getUserName());
                bizEducateDocAttach.setCreateTime(DateUtils.getNowDate());
                bizEducateDocAttachService.insertBizEducateDocAttachNoLogin(bizEducateDocAttach);
                BizEducateDocAttachVO bizEducateDocAttachVO = new BizEducateDocAttachVO();
                BeanUtils.copyProperties(bizEducateDocAttach,bizEducateDocAttachVO);
                bizEducateDocAttachVO.setUrl(url);
                bizEducateDocAttachVO.setFileId(String.valueOf(bizEducateDocAttachVO.getId()));
                bizEducateDocAttachVO.setCreateBy(sysUser.getNickName());
                return AjaxResult.success(bizEducateDocAttachVO);
            } else {
                return AjaxResult.error("上传文件不能为空，请联系管理员");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            if (!file.isEmpty()) {
                if (!FileUtils.checkAllowDownload(file.getOriginalFilename())) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许上传。 ", file.getOriginalFilename()));
                }
                // 上传并返回新文件名称
                String suffixName = FileTypeUtils.getFileType(file);
                Long userId = SecurityUtils.getLoginUser().getUserId();

                String fileName = StringUtils.format("{}_{}_{}.{}",
                        FilenameUtils.getBaseName(file.getOriginalFilename()),
                        userId,
                        Seq.getId(Seq.uploadSeqType), suffixName);
                String url = MinIoUtil.upload(minIoProperties.getBucketName(), fileName, file.getInputStream());
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("fileName", fileName);
                return ajax;
            } else {
                return AjaxResult.error("上传文件不能为空，请联系管理员");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
